from django.shortcuts import render,HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from tools.sms_code import send_message
import string
import random
from captcha.image import ImageCaptcha
import redis
import jwt
from business.models import *
import time
from django.conf import settings
from tools.jwt_decode import login
# Create your views here.
# 商家视图


# 图片验证码的视图
class ImageCodeAPIView(APIView):
    def get(self, request, uuid):
        # 生成一个4位数随机码
        # string.ascii_letters：a-zA-Z所有字母
        # string.digits：数字0-9
        # random.sample：随机采样(返回列表类型)
        code = "".join(random.sample(string.ascii_letters + string.digits, 4))
        # 实例化一个图片验证码对象
        # 用captcha.image下的 ImageCaptcha 生成字符验证码图片
        img = ImageCaptcha()
        # 把这个验证码转换成图片形式的
        image_code = img.generate(code)  # 字节io对象
        # 验证码存入redis
        redis_conn = redis.Redis(host="localhost", port=6379)
        redis_conn.set(uuid, code, ex=5 * 60)

        # 返回响应
        return HttpResponse(image_code, content_type="image/png")


# 获取验证码
class SmsView(APIView):
    def get(self,request,mobile):
        uuid = request.query_params.get('uuid')
        code = request.query_params.get('code')
        if not all([uuid,code]):
            return Response({
                'code':400,
                'msg':'获取数据为空'
            })
        print('>>>>>>>>>>',uuid,code)
        # 取出redis中uuid的值
        redis_conn = redis.Redis(host="localhost", port=6379)
        code_r = redis_conn.get(uuid)
        if not code_r:
            return Response({
                'code':400,
                'msg':'校验码已过期'
            })
        # 验证码还未过期，解码与前端对比
        if code_r.decode().lower() != code.lower():
            return Response({
                "code": 400,
                "msg": "校验码错误"
            })

        send_message(mobile)
        return Response({
            'code':200,
            'msg':'发送成功'
        })


# 手机验证码登入或注册
class UserView(APIView):
    def post(self,request):
        mobile = request.data.get('mobile')
        sms = request.data.get('sms')
        if not all([mobile,sms]):
            return Response({
                'code':400,
                'msg':'获取数据为空'
            })

        # 取出redis中uuid的值
        redis_conn = redis.Redis(host="localhost", port=6379)
        key = 'sms_%s' % mobile
        code_r = redis_conn.get(key)
        if not code_r:
            return Response({
                'code': 400,
                'msg': '验证码已过期'
            })
        # 验证码还未过期，解码与前端对比
        if code_r.decode().lower() != sms.lower():
            return Response({
                "code": 400,
                "msg": "验证码错误"
            })

        # 判断此手机号是否注册
        user = BusUserModel.objects.filter(mobile=mobile)
        if not user:
            # 没有注册，进行注册
            BusUserModel.objects.create(
                mobile=mobile,
            )
        try:
            user = BusUserModel.objects.get(mobile=mobile)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'没有此信息'
            })

        token = jwt.encode({
            'uid':user.id,
            'username':user.b_name,
            'exp':time.time() + 720000
        },key=settings.SECRET_KEY,algorithm='HS256')

        return Response({
            'code':200,
            'msg':'登入成功',
            'token':token
        })


# 对商品类别的增删改查  在平台操作
class ClassifyView(APIView):
    def get(self,request):
        # 获取所有分类
        category = CategoryModel.objects.filter(delete=False)
        category_list = []
        for i in category:
            category_list.append({
                'cid':i.id,
                'c_name':i.c_name,
                'c_img':i.c_img,
            })

        return Response({
            'code':200,
            'msg':'获取分类商品成功',
            'data':category_list,
        })

    def post(self,request):
        c_name = request.data.get('name')
        c_img = request.data.get('img')

        if not all([c_img,c_name]):
            return Response({
                'code':400,
                'msg':'获取的数据为空'
            })

        # 唯一性判断
        category = CategoryModel.objects.filter(c_name=c_name)
        if category:
            return Response({
                'code':400,
                'msg':'已有此分类'
            })

        CategoryModel.objects.create(
            c_name=c_name,
            c_img=c_img,
        )

        return Response({
            'code':200,
            'msg':"添加成功"
        })

# 商品分类的编辑获取删除
class ClassifyInfoView(APIView):
    def get(self,request,id):
        try:
            category = CategoryModel.objects.get(id=id)
            return Response({
                'code':200,
                'msg':'获取成功',
                'data':{
                    'cid':category.id,
                    'c_name':category.c_name,
                    'c_img':category.c_img,
                }
            })
        except Exception as e:
            print(">?>>>>>",e)
            return Response({
                'code':400,
                'msg':'获取商品分类失败'
            })

    def put(self,request,id):
        # 获取前端数据
        c_name = request.data.get('name')
        c_img = request.data.get('img')

        if not all([c_img, c_name]):
            return Response({
                'code': 400,
                'msg': '获取的数据为空'
            })

        try:
            category = CategoryModel.objects.get(id=id)
            category.c_name = c_name
            category.c_img = c_img
            category.save()

            return Response({
                'code':200,
                'msg':'商品分类修改成功'
            })

        except Exception as e:
            print(">?>>>>>",e)
            return Response({
                'code':400,
                'msg':'获取商品分类失败'
            })

    def delete(self,request,id):
        try:
            category = CategoryModel.objects.get(id=id)
            category.delete = True
            category.save()
            return Response({
                'code':200,
                'msg':'删除成功'
            })

        except Exception as e:
            print(">>>>>>>",e)
            return Response({
                'code':400,
                'msg':'没有此分类'
            })


# 商品的增删改查
class GoodsView(APIView):
    def get(self,request):
        goods = GoodsModel.objects.filter(delete=False)
        goods_list = []
        for i in goods:
            goods_list.append({
                'gid':i.id,
                'g_name':i.g_name,
                'volume':i.volume,
                'inventory':i.inventory,
                'price':i.price,
                'img':i.img,
                'category':i.category_id,
                'bus_user':i.bus_user_id,
                'user':{
                    'u_name':i.bus_user.b_name,
                    'portrait':i.bus_user.portrait,
                    'mobile':i.bus_user.mobile,
                    'business_time':i.bus_user.business_time,
                }
            })

        return Response({
            'code':200,
            'msg':'商品获取成功',
            'data':goods_list,
        })

    @login
    def post(self,request):
        # 获取前端数据
        u_id = request.uid
        print('>>>>>>>>>>',u_id)
        g_name = request.data.get('g_name')
        inventory = request.data.get('inventory')
        price = request.data.get('price')
        img = request.data.get('img')
        category = request.data.get('category')
        burdening = request.data.get('burdening')

        print('>>>>>>>>',g_name,inventory,price,img,category)

        if not all([g_name,inventory,price,img,category]):
            return Response({
                'code':400,
                'msg':'获取前端数据失败'
            })

        GoodsModel.objects.create(
            g_name=g_name,
            inventory=inventory,
            price=price,
            img=img,
            category_id=int(category),
            bus_user_id=u_id,
            burdening=burdening,
        )

        return Response({
            'code':200,
            'msg':"菜品添加成功"
        })


# 商品的修改删除获取
class GoodsInfoView(APIView):
    @login
    def get(self,request,id):
        u_id = request.uid
        try:
            good = GoodsModel.objects.get(id=id)
            return Response({
                'code':200,
                'msg':'获取成功',
                'data':{
                    'gid': good.id,
                    'g_name': good.g_name,
                    'volume': good.volume,
                    'inventory': good.inventory,
                    'price': good.price,
                    'img': good.img,
                    'category': good.category_id,
                    'bus_user': good.bus_user_id,
                    'user': {
                        'u_name': good.bus_user.b_name,
                        'portrait': good.bus_user.portrait,
                        'mobile': good.bus_user.mobile,
                        'business_time': good.bus_user.business_time,
                    }
                }
            })
        except Exception as e:
            print('>>>>>>>>>>',e)
            return Response({
                'code':400,
                'msg':'没有此商品'
            })

    @login
    def put(self,request,id):
        g_name = request.data.get('g_name')
        inventory = request.data.get('inventory')
        price = request.data.get('price')
        img = request.data.get('img')
        category = request.data.get('category')

        if not all([g_name,inventory,price,img,category]):
            return Response({
                'code':400,
                'msg':'获取前端数据失败'
            })

        # 判断是不是你的商品
        u_id = request.uid
        try:
            good = GoodsModel.objects.get(id=id)
            if good.bus_user_id == u_id:

                good.g_name = g_name
                good.inventory = inventory
                good.price = price
                good.img = img
                good.category = category
                good.save()

                return Response({
                    'code':200,
                    'msg':'商品修改成功'
                })
            return Response({
                'code':400,
                'msg':'此商品不是你的不可修改'
            })

        except Exception as e:
            print(">?>>>>>",e)
            return Response({
                'code':400,
                'msg':'商品修改失败'
            })

    @login
    def delete(self,request,id):
        u_id = request.uid
        try:
            good = GoodsModel.objects.get(id=id)
            if good.bus_user_id == u_id:

                good.delete = True
                good.save()

                return Response({
                    'code':200,
                    'msg':'删除成功'
                })
            return Response({
                'code':400,
                'msg':'此商品不是你的不可删除'
            })

        except Exception as e:
            print('>>>>>>>>>>>',e)
            return Response({
                'code':400,
                'msg':'删除失败'
            })


# 获取主食分类商品
class CateGoodView(APIView):
    def get(self,request,id):
        # 判断分类是否存在
        try:
            category = CategoryModel.objects.get(id=id)
            print('>>>>>>>>',category)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'获取分类失败'
            })

        goods = GoodsModel.objects.filter(category_id=id)
        goods_list = []
        for i in goods:
            goods_list.append({
                'id':i.id,
                'g_name':i.g_name,
                'volume':i.volume,
                'inventory':i.inventory,
                'price':i.price,
                'img':i.img,
                'category':i.category_id,
                'bus_user':i.bus_user_id,
                'establish_time':i.establish_time,
                'change_time':i.change_time,
                'delete':i.delete,
                'burdening':i.burdening,
            })
        c_name = category.c_name
        return Response({
            'code':200,
            'msg':'获取商品成功',
            'data':goods_list,
            'c_name':c_name
        })


# 获取推荐畅销的商品
class RecommendView(APIView):
    def get(self,request,id):
        if id == 4:
            goods = GoodsModel.objects.filter(is_recommend=True)
            goods_list = []
            for i in goods:
                goods_list.append({
                    'id':i.id,
                    'g_name': i.g_name,
                    'volume': i.volume,
                    'inventory': i.inventory,
                    'price': i.price,
                    'img': i.img,
                    'category': i.category_id,
                    'bus_user': i.bus_user_id,
                    'establish_time': i.establish_time,
                    'change_time': i.change_time,
                    'delete': i.delete,
                    'burdening': i.burdening,
                })
            return Response({
                'code': 200,
                'msg': "获取推荐商品成功",
                'data': goods_list,
            })
        else:
            goods = GoodsModel.objects.filter(is_demand=True)
            goods_list = []
            for i in goods:
                goods_list.append({
                    'id':i.id,
                    'g_name': i.g_name,
                    'volume': i.volume,
                    'inventory': i.inventory,
                    'price': i.price,
                    'img': i.img,
                    'category': i.category_id,
                    'bus_user': i.bus_user_id,
                    'establish_time': i.establish_time,
                    'change_time': i.change_time,
                    'delete': i.delete,
                    'burdening': i.burdening,
                })
            return Response({
                'code':200,
                'msg':"获取推荐商品成功",
                'data':goods_list,
            })

# 获取单个商品
class GoodInfoView(APIView):
    def get(self,request,id):
        try:
            goods = GoodsModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'获取失败'
            })

        return Response({
            'code':200,
            'msg':'获取成功',
            'data':{
                'id': goods.id,
                'g_name': goods.g_name,
                'volume': goods.volume,
                'inventory': goods.inventory,
                'price': goods.price,
                'img': goods.img,
                'category': goods.category_id,
                'bus_user': goods.bus_user_id,
                'establish_time': goods.establish_time,
                'change_time': goods.change_time,
                'delete': goods.delete,
                'burdening': goods.burdening,
            }
        })


